package com.dtguai.app.api.controller.user;


import com.dtguai.app.api.form.user.UserForm;
import com.dtguai.app.base.action.BaseAction;
import com.dtguai.app.common.error.ErrorCode;
import com.dtguai.app.common.validator.BaseAssert;
import com.dtguai.app.common.validator.ValidatorUtils;
import com.dtguai.app.common.validator.group.UpdateGroup;
import com.dtguai.app.model.User;
import com.dtguai.app.protocol.response.ApiResponse;
import com.dtguai.app.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponses;
import lombok.AllArgsConstructor;
import org.modelmapper.ModelMapper;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 用户表
 *
 * @author guo
 * @date 2019-02-15 16:12:24
 */
@RestController
@RequestMapping("/api/v1/user")
@Api(value = "User-用户表-接口", tags = {"User-用户表-接口"})
@AllArgsConstructor
public class UserApi extends BaseAction {

    private final UserService userService;

    /**
     * 分页查询 注意返回信息是 PageInfo 自带分页所有信息
     *
     * @param user 入参对象Form
     * @author guo
     * @date 2019-02-15 16:12:24
     */
    @ApiOperation(value = "分页查询-返回List<User>", notes = "分页查询-返回List<User>")
    @GetMapping(value = "/list", produces = "application/json;charset=UTF-8")
    public ResponseEntity<ApiResponse<List<User>>> list(UserForm user) {
        // 表单校验
        ValidatorUtils.validateEntity(user);
        List<User> userList = userService.selectByPage(user, true, User.class);
        return ResponseEntity.ok(new ApiResponse<>(userList));
    }

    /**
     * 根据主键查询
     *
     * @param id 主键
     * @author guo
     * @date 2019-02-15 16:12:24
     */
    @ApiOperation(value = "根据主键查询", notes = "根据主键查询")
    @GetMapping(value = "/infoByKey", produces = "application/json;charset=UTF-8")
    @ApiResponses({
            @io.swagger.annotations.ApiResponse(code = 1022, message = "id不能为空")
    })
    public ResponseEntity<ApiResponse<User>> infoByKey(Integer id) {
        BaseAssert.isNull(id, ErrorCode.ID_NOT_NULL);
        return ResponseEntity.ok(new ApiResponse<User>(userService.selectByKey(id)));
    }

    /**
     * 更新数据
     *
     * @param user 入参对象Form
     * @author guo
     * @date 2019-02-15 16:12:24
     */
    @ApiOperation(value = "更新", notes = "更新")
    @PostMapping(value = "/update", produces = "application/json;charset=UTF-8")
    public ResponseEntity<ApiResponse<Object>> update(UserForm user) {
        ValidatorUtils.validateEntity(user, UpdateGroup.class);
        userService.updateNotNull(new ModelMapper().map(user, User.class));
        return ResponseEntity.ok(new ApiResponse<>());
    }


}